package com.sgb.kjwl.view.ui.fragment.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentEnterpriseItemBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.enterprise.CompanyListEntity;
import com.sgb.kjwl.model.entity.enterprise.CopyrightListEntity2;
import com.sgb.kjwl.model.entity.enterprise.EpQuoteEntity;
import com.sgb.kjwl.model.entity.enterprise.IntellpropEntity;
import com.sgb.kjwl.model.entity.enterprise.ListBean;
import com.sgb.kjwl.model.entity.enterprise.NeedEntity;
import com.sgb.kjwl.model.entity.enterprise.PatentEntity;
import com.sgb.kjwl.model.entity.enterprise.TeamChangeEntity;
import com.sgb.link.event.LeaseEvent;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.enterprise.MakeOverDetailActivity;
//import com.sgb.kjwl.view.ui.activity.enterprise.NeedDetailsActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.NewNeedDetailsActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.ProfessionalQuoteDetailActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.ProfessionalTeamDetailActivity;
import com.sgb.kjwl.view.ui.adapter.enterprise.EpCompanyAdapter;
import com.sgb.kjwl.view.ui.adapter.enterprise.HomeCopyrightAdapter;
import com.sgb.kjwl.view.ui.adapter.enterprise.HomeNeedAdapter;
import com.sgb.kjwl.view.ui.adapter.enterprise.HomePatentAdapter;
import com.sgb.kjwl.view.ui.adapter.enterprise.HomeQuoteAdapter;
import com.sgb.kjwl.view.ui.adapter.enterprise.HomeTeamAdapter;
import com.sgb.kjwl.view.ui.adapter.enterprise.HomeTradeMarkAdapter;
import com.sgb.kjwl.viewmodel.home.EnterpriseItemFragModel;
import com.swgk.core.base.di.AppComponent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class EnterpriseItemFragment extends AppLazyFragment {
    @Inject
    EnterpriseItemFragModel mModel;
    private FragmentEnterpriseItemBinding mBind;
    private HomeTradeMarkAdapter homeTradeMarkAdapter;//商标
    private HomePatentAdapter patentAdapter;//专利
    private HomeCopyrightAdapter ipCopyrightAdapter;//版权
    private HomeQuoteAdapter epQuoteAdapter;//服务
    private HomeTeamAdapter epTeamAdapter;//团队
    private EpCompanyAdapter epCompanyAdapter;
    private HomeNeedAdapter mNeedAdapter;//需求大厅
    private int mTypeIndex;//区分精品商标 热门版权 优质专利 专业服务、专业团队
    private List<IntellpropEntity> mListMark;
    private int mPageMark = 1;
    private List<CopyrightListEntity2> mListCopyright;
    private int mPageCopyright = 1;
    private List<PatentEntity> mListPantent;
    private int mPagePatent = 1;
    private List<EpQuoteEntity> mListService;
    private int mPageService = 1;
    private List<TeamChangeEntity> mListTeam;
    private int mPageTeam = 1;
    private List<ListBean> mListNeed;
    private int mPageNeed = 1;

    public static EnterpriseItemFragment newInstance(int position) {
        EnterpriseItemFragment fragment = new EnterpriseItemFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("TYPE_INDEX", position);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBind = DataBindingUtil.inflate(inflater, R.layout.fragment_enterprise_item, container, false);
        return mBind.getRoot();
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        if (getArguments() != null) {
            mTypeIndex = getArguments().getInt("TYPE_INDEX");
        }
        mBind.displayView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBind.srlEnterpriseList.setEnableRefresh(false);
        mBind.srlEnterpriseList.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                switch (mTypeIndex) {
                    case 0: //需求
                        mModel.getDemandHallList(mPageNeed);
                        break;
                    case 1: // 精品商标
                        mModel.getTrademarkList(mPageMark);
                        break;
                    case 2: //热门版权
                        mModel.getCopyrightList(mPageCopyright);
                        break;
                    case 3: //优质专利
                        mModel.getPatentList(mPagePatent);
                        break;
                    case 4: //专业服务
                        mModel.getOfferList(mPageService);
                        break;
                    case 5: //专业团队
                        mModel.getTeamList(mPageTeam);
                        break;
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                switch (mTypeIndex) {
                    case 0: //需求
                        mModel.getDemandHallList(mPageNeed);
                        break;
                    case 1: // 精品商标
                        mModel.getTrademarkList(mPageMark);
                        break;
                    case 2: //热门版权
                        mModel.getCopyrightList(mPageCopyright);
                        break;
                    case 3: //优质专利
                        mModel.getPatentList(mPagePatent);
                        break;
                    case 4: //专业服务
                        mModel.getOfferList(mPageService);
                        break;
                    case 5: //专业团队
                        mModel.getTeamList(mPageTeam);
                        break;
                }
            }
        });
        initAdapter();
    }

    private void initAdapter() {
        switch (mTypeIndex) {
            case 0://需求大厅
                mListNeed = new ArrayList<>();
                mNeedAdapter = new HomeNeedAdapter(mListNeed);
                mBind.displayView.setAdapter(mNeedAdapter);
                mNeedAdapter.setOnItemClickListener((adapter, view, position) -> {
                    ListBean listBean = mListNeed.get(position);
                    NewNeedDetailsActivity.startactivity(getActivity(), listBean.id + "");
                });

//                mNeedAdapter.setmAskClick(item -> {
//                    if (DialogHelper.checkLogin()) {
//                        DialogHelper.showDialog(getContext(), "确认呼叫", item.linkMan + "：" + item.linkmanPhone, "确定", new DialogFunction() {
//                            @Override
//                            public void normalRoundDialog() {
//                                ActivityJump.jumpToPhone(getContext(), item.linkmanPhone);
//                            }
//                        });
//                    } else {
//                        DialogHelper.showLoginDialogNew(getContext(), EventConstant.EVENT_ENTERPRISE_ITEM_QUOTE_FRG_JUMP, "温馨提示", "登录后可拨打电话,去登录", "登录");
//                    }
//                });
                break;
            case 1://精品商标
                mListMark = new ArrayList<>();
                if (homeTradeMarkAdapter == null) {
                    homeTradeMarkAdapter = new HomeTradeMarkAdapter(getActivity(), mListMark);
                }
                mBind.displayView.setAdapter(homeTradeMarkAdapter);
                homeTradeMarkAdapter.setOnItemClickListener((adapter, view, position) -> {
                    IntellpropEntity intellpropEntity = mListMark.get(position);
                    ActivityJump.jumpToActivity(getActivity(), MakeOverDetailActivity.class, Pair.create("detail", "商标"), Pair.create("id", intellpropEntity.getId()));
                });
                break;
            case 2://热门版权
                mListCopyright = new ArrayList<>();
                if (ipCopyrightAdapter == null) {
                    ipCopyrightAdapter = new HomeCopyrightAdapter(getActivity(), mListCopyright);
                }
                mBind.displayView.setAdapter(ipCopyrightAdapter);
                ipCopyrightAdapter.setOnItemClickListener((adapter, view, position) -> {
                    CopyrightListEntity2 copyrightListEntity2 = mListCopyright.get(position);
                    ActivityJump.jumpToActivity(getActivity(), MakeOverDetailActivity.class, Pair.create("detail", "版权"), Pair.create("id", copyrightListEntity2.getId()));
                });
                break;
            case 3://优质专利
                mListPantent = new ArrayList<>();
                if (patentAdapter == null) {
                    patentAdapter = new HomePatentAdapter(getActivity(), mListPantent);
                }
                mBind.displayView.setAdapter(patentAdapter);
                patentAdapter.setOnItemClickListener((adapter, view, position) -> {
                    PatentEntity patentEntity = mListPantent.get(position);
                    ActivityJump.jumpToActivity(getActivity(), MakeOverDetailActivity.class, Pair.create("detail", "专利"), Pair.create("id", patentEntity.getId()));
                });
                break;
            case 4://专业服务
                mListService = new ArrayList<>();
                epQuoteAdapter = new HomeQuoteAdapter(mListService);
                mBind.displayView.setAdapter(epQuoteAdapter);
                epQuoteAdapter.OnCallPhone((num, name) -> {
                    if (DialogHelper.checkLogin()) {
                        DialogHelper.showDialog(getContext(), "确认呼叫", name + ":" + num, "确定", new DialogFunction() {
                            @Override
                            public void normalRoundDialog() {
                                ActivityJump.jumpToPhone(getContext(), num);
                            }
                        });
                    } else {
                        DialogHelper.showLoginDialogNew(getContext(), EventConstant.EVENT_ENTERPRISE_ITEM_QUOTE_FRG_JUMP, "温馨提示", "登录后可拨打电话,去登录", "登录");
                    }
                });
                epQuoteAdapter.setOnItemClickListener((adapter, view, position) -> {
                    EpQuoteEntity epQuoteEntity = mListService.get(position);
                    ProfessionalQuoteDetailActivity.start(getContext(), Long.parseLong(epQuoteEntity.getId()));
                });
                break;
            case 5://专业团队
                mListTeam = new ArrayList<>();
                epTeamAdapter = new HomeTeamAdapter(mListTeam);
                mBind.displayView.setAdapter(epTeamAdapter);
                epTeamAdapter.OnCallPhone((num, name) -> {
                    if (DialogHelper.checkLogin()) {
                        DialogHelper.showDialog(getContext(), "确认呼叫", name + ":" + num, "确定", new DialogFunction() {
                            @Override
                            public void normalRoundDialog() {
                                ActivityJump.jumpToPhone(getContext(), num);
                            }
                        });
                    } else {
                        DialogHelper.showLoginDialogNew(getContext(), EventConstant.EVENT_ENTERPRISE_ITEM_QUOTE_FRG_JUMP, "温馨提示", "登录后可拨打电话,去登录", "登录");
                    }
                });
                epTeamAdapter.setOnItemClickListener((adapter, view, position) -> {
                    TeamChangeEntity epTeamEntity = mListTeam.get(position);
                    ActivityJump.jumpToActivity(getActivity(), ProfessionalTeamDetailActivity.class, Pair.create("id", epTeamEntity.getId()));
                });
                break;
        }
    }

    @Override
    protected void onLazyLoad() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if(mModel == null) return;
        switch (mTypeIndex) {
            case 0: //需求
                mPageNeed = 1;
                mModel.getDemandHallList(mPageNeed);
                break;
            case 1: // 精品商标
                mPageMark = 1;
                mModel.getTrademarkList(mPageMark);
                break;
            case 2: //热门版权
                mPageCopyright = 1;
                mModel.getCopyrightList(mPageCopyright);
                break;
            case 3: //优质专利
                mPagePatent = 1;
                mModel.getPatentList(mPagePatent);
                break;
            case 4: //专业服务
                mPageService = 1;
                mModel.getOfferList(mPageService);
                break;
            case 5: //专业团队
                mPageTeam = 1;
                mModel.getTeamList(mPageTeam);
                break;
        }
    }

    /**
     * 商标数据
     *
     * @param list
     */
    public void showTrademarkList(ListResponse<List<IntellpropEntity>> list) {
        mBind.srlEnterpriseList.finishRefresh();
        mBind.srlEnterpriseList.finishLoadMore();
        if (mPageMark == 1) {
            mListMark.clear();
        }
        if (list.getList() != null) {
            mListMark.addAll(list.getList());
        }
        homeTradeMarkAdapter.notifyDataSetChanged();
        //判断列表是否为null
        if (mListMark.size() == 0) {
            mBind.srlEnterpriseList.setVisibility(View.GONE);
            mBind.errorView.setVisibility(View.VISIBLE);
        } else {
            mBind.srlEnterpriseList.setVisibility(View.VISIBLE);
            mBind.errorView.setVisibility(View.GONE);
        }
        //
        if (list.getList().size()<10) {
            mBind.srlEnterpriseList.finishLoadMoreWithNoMoreData();
        } else {
            mPageMark = mPageMark + 1;
            mBind.srlEnterpriseList.resetNoMoreData();
        }
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof EnterpriseFragment) {
            ((EnterpriseFragment) parentFragment).hideRefresh();
        }
    }

    /**
     * 专利数据
     *
     * @param list
     */
    public void showPatentList(ListResponse<List<PatentEntity>> list) {
        mBind.srlEnterpriseList.finishRefresh();
        mBind.srlEnterpriseList.finishLoadMore();
        if (mPagePatent == 1) {
            mListPantent.clear();
        }
        if (list.getList() != null) {
            mListPantent.addAll(list.getList());
        }
        patentAdapter.notifyDataSetChanged();
        //判断列表是否为null
        if (mListPantent.size() == 0) {
            mBind.srlEnterpriseList.setVisibility(View.GONE);
            mBind.errorView.setVisibility(View.VISIBLE);
        } else {
            mBind.srlEnterpriseList.setVisibility(View.VISIBLE);
            mBind.errorView.setVisibility(View.GONE);
        }
        //
        if (mPagePatent < list.getTotal()) {
            mPagePatent = mPagePatent + 1;
            mBind.srlEnterpriseList.resetNoMoreData();
        } else {
            mBind.srlEnterpriseList.finishLoadMoreWithNoMoreData();
        }
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof EnterpriseFragment) {
            ((EnterpriseFragment) parentFragment).hideRefresh();
        }
    }

    /**
     * 版本数据
     *
     * @param list
     */
    public void showCopyrightList(ListResponse<List<CopyrightListEntity2>> list) {
        mBind.srlEnterpriseList.finishRefresh();
        mBind.srlEnterpriseList.finishLoadMore();
        if (mPageCopyright == 1) {
            mListCopyright.clear();
        }
        if (list.getList() != null) {
            mListCopyright.addAll(list.getList());
        }
        ipCopyrightAdapter.notifyDataSetChanged();
        //判断列表是否为null
        if (mListCopyright.size() == 0) {
            mBind.srlEnterpriseList.setVisibility(View.GONE);
            mBind.errorView.setVisibility(View.VISIBLE);
        } else {
            mBind.srlEnterpriseList.setVisibility(View.VISIBLE);
            mBind.errorView.setVisibility(View.GONE);
        }
        //
        if (mPageCopyright < list.getTotal()) {
            mPageCopyright = mPageCopyright + 1;
            mBind.srlEnterpriseList.resetNoMoreData();
        } else {
            mBind.srlEnterpriseList.finishLoadMoreWithNoMoreData();
        }
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof EnterpriseFragment) {
            ((EnterpriseFragment) parentFragment).hideRefresh();
        }
    }


    /**
     * 热门交易-公司数据
     *
     * @param list
     * @param isLoadMore
     */
    public void showCompanyList(List<CompanyListEntity> list, boolean isLoadMore) {
        if (isLoadMore) {
            if (null != list && list.size() > 0) {
                epCompanyAdapter.addDatas(list);
            }
            mBind.displayView.setVisibility(View.VISIBLE);
        } else {
            if (null != list && list.size() > 0) {
                mBind.displayView.setVisibility(View.VISIBLE);
                mBind.errorView.setVisibility(View.GONE);
                epCompanyAdapter.setDatas(list);
            } else {
                epCompanyAdapter.setDatas(null);
                mBind.displayView.setVisibility(View.GONE);
                mBind.errorView.setVisibility(View.VISIBLE);
            }
        }
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof EnterpriseFragment) {
            ((EnterpriseFragment) parentFragment).hideRefresh();
        }
    }

    /**
     * 专业报价数据
     *
     * @param list
     */
    public void showQuoteList(ListResponse<List<EpQuoteEntity>> list) {
        mBind.srlEnterpriseList.finishRefresh();
        mBind.srlEnterpriseList.finishLoadMore();
        if (mPageService == 1) {
            mListService.clear();
        }
        if (list.getList() != null) {
            mListService.addAll(list.getList());
        }
        epQuoteAdapter.notifyDataSetChanged();
        //判断列表是否为null
        if (mListService.size() == 0) {
            mBind.srlEnterpriseList.setVisibility(View.GONE);
            mBind.errorView.setVisibility(View.VISIBLE);
        } else {
            mBind.srlEnterpriseList.setVisibility(View.VISIBLE);
            mBind.errorView.setVisibility(View.GONE);
        }
        //
        if (mPageService < list.getTotal()) {
            mPageService = mPageService + 1;
            mBind.srlEnterpriseList.resetNoMoreData();
        } else {
            mBind.srlEnterpriseList.finishLoadMoreWithNoMoreData();
        }
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof EnterpriseFragment) {
            ((EnterpriseFragment) parentFragment).hideRefresh();
        }
    }


    /**
     * 专业团队数据
     *
     * @param list
     */
    public void showTeamList(ListResponse<List<TeamChangeEntity>> list) {
        mBind.srlEnterpriseList.finishRefresh();
        mBind.srlEnterpriseList.finishLoadMore();
        if (mPageTeam == 1) {
            mListTeam.clear();
        }
        if (list.getList() != null) {
            mListTeam.addAll(list.getList());
        }
        epTeamAdapter.notifyDataSetChanged();
        //判断列表是否为null
        if (mListTeam.size() == 0) {
            mBind.srlEnterpriseList.setVisibility(View.GONE);
            mBind.errorView.setVisibility(View.VISIBLE);
        } else {
            mBind.srlEnterpriseList.setVisibility(View.VISIBLE);
            mBind.errorView.setVisibility(View.GONE);
        }
        //
        if (mPageTeam < list.getTotal()) {
            mPageTeam = mPageTeam + 1;
            mBind.srlEnterpriseList.resetNoMoreData();
        } else {
            mBind.srlEnterpriseList.finishLoadMoreWithNoMoreData();
        }
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof EnterpriseFragment) {
            ((EnterpriseFragment) parentFragment).hideRefresh();
        }
    }

    /**
     * 需求大厅列表
     */
    public void getDemandHallList(NeedEntity list) {
        if (mNeedAdapter == null) return;
        mBind.srlEnterpriseList.finishRefresh();
        mBind.srlEnterpriseList.finishLoadMore();
        if (mPageNeed == 1) {
            mListNeed.clear();
        }
        if (list.list != null) {
            mListNeed.addAll(list.list);
        }
        mNeedAdapter.notifyDataSetChanged();
        //判断列表是否为null
        if (mListNeed.size() == 0) {
            mBind.srlEnterpriseList.setVisibility(View.GONE);
            mBind.errorView.setVisibility(View.VISIBLE);
        } else {
            mBind.srlEnterpriseList.setVisibility(View.VISIBLE);
            mBind.errorView.setVisibility(View.GONE);
        }
        //
        if (mPageNeed < list.totalPage) {
            mPageNeed = mPageNeed + 1;
            mBind.srlEnterpriseList.resetNoMoreData();
        } else {
            mBind.srlEnterpriseList.finishLoadMoreWithNoMoreData();
        }
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof EnterpriseFragment) {
            ((EnterpriseFragment) parentFragment).hideRefresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(ChooseAreaEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CHOOSE_AERA) {
            onLazyLoad();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LoginEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ENTERPRISE_ITEM_QUOTE_FRG_JUMP) {
            onLazyLoad();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onEvent(LeaseEvent event){
        if (event.getMessageTag() == EventConstant.EVENT_CREATE_MAKEOVERORDER_SECESS) {
            onLazyLoad();
        }
    }


    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
